# -*- coding: utf-8 -*-
from model import Collection, db


class Problem(Collection):
    '''
* `_id` (ObjectId) - ID of problem
* `askTo` (string) - 被询问的老师的 ID (可能为空)
* `commentNum` (int) - 评论数
* `content` (string) - content of problem
* `image` (string) - Url of image
* `answerList ([string]) - 老师的回答列表
* `commentList ([string]) - 学生的评论列表
* `zan` (int) - the number of zan
* `viewNum` (int) - 被点击的次数
* `answerNum` (int) - 回答问题的老师数
* `timestamp` (long) - timestamp
* `userId` (string) - ID of user the problem belongs
* `zanList` (dict) - 点赞的人的列表
    '''

    collection = db.problem

    class Field(object):
        _id = '_id'
        askTo = 'askTo'
        commentNum = 'commentNum'
        content = 'content'
        image = 'image'
        answerList = 'answerList'
        commentList = 'commentList'
        tag = 'tag'
        zan = 'zan'
        viewNum = 'viewNum'
        answerNum = 'answerNum'
        timestamp = 'timestamp'
        userId = 'userId'
        zanList = 'zanList'

    @staticmethod
    def new_problem(ask_to, content, image, tag, timestamp, user_id):
        return Problem.insert({
            Problem.Field.askTo: ask_to,
            Problem.Field.commentNum: 0,
            Problem.Field.content: content,
            Problem.Field.image: image,
            Problem.Field.answerList: [],
            Problem.Field.commentList: [],
            Problem.Field.zan: 0,
            Problem.Field.tag: tag,
            Problem.Field.viewNum: 0,
            Problem.Field.answerNum: 0,
            Problem.Field.timestamp: timestamp,
            Problem.Field.userId: user_id,
            Problem.Field.zanList: {}
        })

    @staticmethod
    def update_zan(problem_id, user_id, zan):
        problem = Problem.get({
            Problem.Field._id: problem_id
        }, [
            Problem.Field.zanList
        ])
        zan_list = problem.data.get(Problem.Field.zanList)
        if zan == 1:
            if zan_list.get(user_id):
                return True
            problem.update({
                '$set': {
                    Problem.Field.zanList + '.' + user_id: 1
                },
                '$inc': {
                    Problem.Field.zan: zan
                }
            })
        elif zan == -1:
            if not zan_list.get(user_id):
                return True
            problem.update({
                '$unset': {
                    Problem.Field.zanList + '.' + user_id: 1
                },
                '$inc': {
                    Problem.Field.zan: zan
                }
            })
        return True
